package com.qfedu.spring.anno.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author zhang
 * @Title: commonValidateAdd
 * @date : 2022/4/28 15:26
 * spring的配置类
 * 作用：是替换之前bean.xml 配置文件
 */
@Configuration // 表示当前类是一个配置类
@ComponentScan("com.qfedu.spring.anno")
public class SpringConfig {

    /**
     * 1.dataSource
     * @Bean : 定义一个bean，方法名datasource 就是bean的id,方法的返回值就是class
     *  <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" />
     */
    @Bean
    public DruidDataSource dataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/db2202?useUnicode=true&characterEncoding=UTF-8");
        dataSource.setUsername("root");
        dataSource.setPassword("235886");
        return dataSource;
    }

    // 2. sqlSessionFactory
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory() throws IOException {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        //注入数据源
        factoryBean.setDataSource(dataSource());
        //获取mapper.xml资源文件
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        //获取mapper.xml解析路径,返回的是数组
        Resource[] resources = resolver.getResources("classpath:mapper/*.xml");
        // 注入资源文件
        factoryBean.setMapperLocations(resources);
        //配置实体类的别名
        factoryBean.setTypeAliasesPackage("com.qfedu.spring.anno.entity");
        return factoryBean;

    }
    // MapperScannerConfigurer
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer configurer = new MapperScannerConfigurer();
        // 配置dao 层接口的包名
        configurer.setBasePackage("com.qfedu.spring.anno.dao");
        return configurer;
    }
}
